package com.fulihui.wgj.admin.api.material;

import com.fulihui.common.builder.web.JsonResultBuilder;
import com.fulihui.common.enums.MaterialTypeEnum;
import com.fulihui.common.result.web.PageView;
import com.fulihui.common.result.web.Result;
import com.fulihui.common.util.DateUtils;
import com.fulihui.weixinsdk.WeixinSDK;
import com.fulihui.weixinsdk.request.material.MaterialAddRequest;
import com.fulihui.weixinsdk.result.material.MaterialAddResult;
import com.fulihui.wgj.admin.api.base.BaseController;
import com.fulihui.wgj.admin.api.material.request.MaterialPageRequest;
import com.fulihui.wgj.admin.api.material.vo.MaterialImageVO;
import com.fulihui.wgj.admin.api.material.vo.MaterialNewsVO;
import com.fulihui.wgj.admin.config.properties.AdminProperties;
import com.fulihui.wgj.admin.integration.MaterialServiceClient;
import com.fulihui.wgj.admin.integration.WxPlatformClient;
import com.fulihui.wgj.facade.request.material.WxMaterialRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

import static com.fulihui.common.error.Errors.WxSystemConfigError.GET_TOKEN_FAILED;

/**
 * @author: Levon
 * @date: 2018-07-11 15:24
 */
@RestController
@RequestMapping("/material")
@Api(tags = "微信素材相关接口")
public class MaterialManageController extends BaseController {

    @Autowired
    private MaterialServiceClient materialServiceClient;

    @Autowired
    private WeixinSDK weixinSDK;

    @Autowired
    private WxPlatformClient wxPlatformClient;

    @Autowired
    AdminProperties adminProperties;

    @PostMapping("/news/list")
    @ApiOperation("分页获取图文素材列表")
    public Result<PageView<MaterialNewsVO>> queryNewsList(@RequestBody @Valid MaterialPageRequest request, BindingResult validResult,
                                                          HttpServletRequest servletRequest) {
        Result valid = valid(validResult);
        if (Objects.nonNull(valid)) {
            return valid;
        }
        request.setAppId(getAppid(servletRequest));
        PageView<MaterialNewsVO> listPageView = materialServiceClient.queryNewsPage(request);

        return JsonResultBuilder.succ(listPageView);
    }

    @PostMapping("/image/list")
    @ApiOperation("分页获取图片素材列表")
    public Result<PageView<MaterialImageVO>> queryImageList(@RequestBody @Valid MaterialPageRequest request, BindingResult validResult,
                                                            HttpServletRequest servletRequest) {
        Result valid = valid(validResult);
        if (Objects.nonNull(valid)) {
            return valid;
        }
        request.setAppId(getAppid(servletRequest));
        PageView<MaterialImageVO> listPageView = materialServiceClient.queryImagePage(request);

        return JsonResultBuilder.succ(listPageView);
    }

    @RequestMapping(value = "/sync", method = RequestMethod.POST)
    @ApiOperation("同步图文素材")
    public Result<Boolean> send(HttpServletRequest servletRequest) {
        return materialServiceClient.syncMaterial(getAppid(servletRequest), MaterialTypeEnum.news.getCode());
    }


    @RequestMapping(value = "/add/image", method = RequestMethod.POST)
    @ApiOperation("上传图片素材")
    public Result<MaterialImageVO> uploadImage(@RequestParam("imgFile") MultipartFile multfile, HttpServletRequest servletRequest) {

        String appid = servletRequest.getParameter("appid");
        String accessToken = wxPlatformClient.queryTokenFromRedis(appid);
        if (StringUtils.isBlank(accessToken)) {
            return JsonResultBuilder.fail(GET_TOKEN_FAILED.getErrcode(), GET_TOKEN_FAILED.getErrmsg());
        }

        String fileName = multfile.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));

        File file = null;
        try {
            file = File.createTempFile(UUID.randomUUID().toString(), prefix);
            multfile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MaterialAddRequest request = new MaterialAddRequest();
        request.setAccess_token(accessToken);
        request.setMedia(file);
        request.setType("image");
        MaterialAddResult materialAddResult = weixinSDK.invokeService(request);

        deleteFile(file);

        if (materialAddResult.isSuccess()) {
            // 上传图片到微信服务器成功之后 需要本地数据库同步素材信息
            WxMaterialRequest wxMaterialRequest = new WxMaterialRequest();
            wxMaterialRequest.setAppId(appid);
            wxMaterialRequest.setMediaId(materialAddResult.getMedia_id());
            wxMaterialRequest.setImageUrl(materialAddResult.getUrl());
            wxMaterialRequest.setType(MaterialTypeEnum.image.getCode());
            wxMaterialRequest.setUpdateTime(new Date());
            materialServiceClient.saveWxMaterial(wxMaterialRequest);

            MaterialImageVO imageVO = new MaterialImageVO();
            imageVO.setUpdateTime(DateUtils.format(new Date(), DateUtils.noSecondFormat));
            imageVO.setMediaId(materialAddResult.getMedia_id());
            imageVO.setImgUrl(adminProperties.getImgproxy() + materialAddResult.getUrl());
            return JsonResultBuilder.succ(imageVO);
        }
        return JsonResultBuilder.fail(500, materialAddResult.getErrmsg());
    }

    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

}